import { createSlice, Dispatch } from '@reduxjs/toolkit';

export type taskItem = {
  id: string;
  state: number;
  complete: string;
};

const taskList: taskItem[] = [];

const taskSlice = createSlice({
  name: 'task',
  initialState: {
    taskList: taskList,
  },
  reducers: {
    getTaskList(state, actions) {
      console.log('actions', actions);

      state.taskList = actions.payload;
    },
    removeTask(state, { payload }) {
      let taskList = state.taskList;
      if (!Array.isArray(taskList)) return;
      state.taskList = taskList.filter(
        (item: { id: string }) => item.id !== payload.id
      );
    },
    updateTask(state, { payload }) {
      let taskList = state.taskList;
      if (!Array.isArray(taskList)) return;
      state.taskList = taskList.map((item) => {
        if (+item.id === +payload.id) {
          item.state = 2;
          item.complete = new Date().toLocaleDateString('zh-CN');
        }
        return item;
      });
    },
  },
});

export let { getTaskList, removeTask, updateTask } = taskSlice.actions;

export const getTaskListAsync = (): any => {
  return async (dispatch: Dispatch) => {
    let list = [
      {
        id: 1,
        state: 0,
        complete: new Date().toLocaleDateString('zh-CN'),
      },
    ];
    dispatch(getTaskList(list));
  };
};

export default taskSlice.reducer;
